package com.pig4cloud.pig.module.service.electric.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.module.api.entity.Parameter;
import com.pig4cloud.pig.module.api.entity.electric.ElectricMeter;
import com.pig4cloud.pig.module.api.entity.electric.ElectricOpRecord;
import com.pig4cloud.pig.module.api.entity.electric.ElectricOrder;
import com.pig4cloud.pig.module.mapper.electric.ElectricMeterMapper;
import com.pig4cloud.pig.module.mapper.electric.ElectricOpRecordMapper;
import com.pig4cloud.pig.module.mapper.electric.ElectricOrderMapper;
import com.pig4cloud.pig.module.service.base.IParameterService;
import com.pig4cloud.pig.module.service.electric.IElectricMeterService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.util.ElectricMeterUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 水电Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-01
 */
@Service
public class ElectricMeterServiceImpl extends ServiceImpl<ElectricMeterMapper, ElectricMeter> implements IElectricMeterService {

	@Resource
	private ElectricMeterMapper meterMapper;
	@Resource
	private ElectricOpRecordMapper opRecordMapper;
	@Resource
	private ElectricOrderMapper orderMapper;
	@Resource
	private IParameterService parameterService;
	@Resource
	private IWxTemplateService wxTemplateService;

	@Value("${web.electric_notify_url}")
	private String electric_notify_url;


	@Override
	@Transactional
	public void notifyOp(String responseContent, List<Map<String, Object>> responseContentList) {
		try{
			if(CollUtil.isNotEmpty(responseContentList)){
				for (Map<String, Object> map : responseContentList){
					String oprId = map.containsKey("opr_id") ? map.get("opr_id").toString() : "";
					ElectricOpRecord opRecord = opRecordMapper.selectOneByColumn("opr_id",oprId);
					if(opRecord != null) {
						opRecord.setResponseContent(responseContent);
						opRecord.setState(1);
						opRecord.setResponseTime(new Date());

						String status = map.containsKey("status") ? map.get("status").toString() : "FAIL";
						opRecord.setStatusCode(status);

						int ret = opRecordMapper.updateById(opRecord);
						if (ret <= 0) {
							throw new TransactionalException("opRecordMapper insert error");
						}


						ElectricMeter meter = meterMapper.selectById(opRecord.getElectricId());
						if (meter != null  && status.equals("SUCCESS")){
							if (opRecord.getOpType().equals("ele_read")) {//抄表
								JSONObject jsonObject = new JSONObject();
								JSONArray data = map.containsKey("data") ? JSONUtil.parseArray(map.get("data").toString()) : null;
								if(data !=null && data.size() > 0){
									jsonObject = (JSONObject)data.get(0);
								}
								if (opRecord.getTypeCode() == 3) {//正向有功总电能

									//[{"opr_id":"86e17e99712e45d98a6f8d5c7d971450","resolve_time":"2022-09-01 11:44:03","status":"SUCCESS",
									// "data":[{"type":3,"value":["20.00"],"dsp":" 购电次数: 0   剩余金额: 0.00 元  总用电量: 20.00 kWh "}]}]

								} else if (opRecord.getTypeCode() == 22) {//剩余金额
									//[{"opr_id":"1053ed6554684b09a703deb0be440c98","resolve_time":"2022-09-01 13:39:38","status":"SUCCESS",
									// "data":[{"type":22,"value":["0.00"],"dsp":" 购电次数: 0   剩余金额: 0.00 元  总用电量: 20.00 kWh "}]}]
									//剩余账户余额
									double value = jsonObject.containsKey("value") ? Double.parseDouble(jsonObject.getJSONArray("value").get(0).toString()) : 0d;
									System.out.println("剩余账户余额: " + value);
									meter.setAccountMoney(new BigDecimal(value));
									//剩余电量 concentrator_sn
									double leftElectricityCount = value / meter.getSinglePrice().doubleValue();
									meter.setElectricityCount(new BigDecimal(leftElectricityCount));

									if(opRecord.getOrderId()!= null && opRecord.getOrderId() > 0){
										ElectricOrder order = orderMapper.selectById(opRecord.getOrderId());
										if(order!=null){
											wxTemplateService.sendWxMsgElectricRecharge(order,1);
										}
									}
									meter.setLastQueryTime(new Date());
								} else if (opRecord.getTypeCode() == 35) {//读取费率电价
									//[{"opr_id":"bf7652e595f54a179fea60873104035d","resolve_time":"2022-09-01 13:37:17","status":"SUCCESS",
									// "data":[{"type":35,"value":["1.0000"],"dsp":"1.0000 元/kWh"}]}]

									double value = jsonObject.containsKey("value") ? Double.parseDouble(jsonObject.getJSONArray("value").get(0).toString()) : 0d;
									System.out.println("读取费率电价： " + value);
									meter.setSinglePrice(new BigDecimal(value));

								} else if (opRecord.getTypeCode() == 38) {//读取一级报警金额
									//[{"opr_id":"37e686edc8e944c7bd53a16513995a8f","resolve_time":"2022-09-01 13:40:36","status":"SUCCESS",
									// "data":[{"type":38,"value":["30.00"],"dsp":"30.00 元"}]}]
									double value = jsonObject.containsKey("value") ? Double.parseDouble(jsonObject.getJSONArray("value").get(0).toString()) : 0d;
									System.out.println("读取一级报警金额： " + value);
									meter.setWarnTipOne(new BigDecimal(value));
								} else if (opRecord.getTypeCode() == 39) {//读取二级报警
									//[{"opr_id":"b54c13a86e3348a0be2d430e61f62161","resolve_time":"2022-09-01 13:41:33","status":"SUCCESS",
									// "data":[{"type":39,"value":["0.00"],"dsp":"0.00 元"}]}]
									double value = jsonObject.containsKey("value") ? Double.parseDouble(jsonObject.getJSONArray("value").get(0).toString()) : 0d;
									System.out.println("读取二级报警： " + value);
									meter.setWarnTipTwo(new BigDecimal(value));
								} else if (opRecord.getTypeCode() == 106) {//查询继电器状态  开合闸的状态
									//[{"opr_id":"1d26b6b6024f4f5e8beb019a73f24176","resolve_time":"2022-09-01 13:42:08","status":"SUCCESS",
									// "data":[{"type":106,"value":["1"],"dsp":"有功功率:反向 已透支 继电器状态:断 继电器命令状态:断 "}]}]
									int value = jsonObject.containsKey("value") ? Integer.parseInt(jsonObject.getJSONArray("value").get(0).toString()) : 0;
									System.out.println("开合闸的状态： " + value);
									meter.setGateState(value);
								}
								ret = meterMapper.updateById(meter);

							} else if (opRecord.getOpType().equals("ele_control_open")) {//合闸

								getSearchData(meter,106);

							} else if (opRecord.getOpType().equals("ele_control_close")) {//拉闸

								getSearchData(meter,106);

							} else if (opRecord.getOpType().equals("reset")) {//电表清零
								meter.setPayCount(1);
								meter.setElectricityCount(new BigDecimal(0));
								meter.setAccountMoney(new BigDecimal(0));
								ret = meterMapper.updateById(meter);
							} else if (opRecord.getOpType().equals("open_account_async")) {//开户

								//[{"opr_id":"84ea11d6594d4e7c9520a7217c80353c","resolve_time":"2022-09-02 10:13:42","status":"SUCCESS",
								// "params":{"display_warning":30,"count":"1","account_id":"1","money":100,"price":0.5469,"pulloff_warning":30},
								// "data":[{"type":8,"value":["100.00"],"dsp":"剩余金额 100.00元 (0.5469 元/kwh,变比1倍)"}]}]
								JSONObject paramsJsonObject = map.containsKey("params") ? JSONUtil.parseObj(map.get("params").toString()) : null;
								if(paramsJsonObject!=null){
									//剩余账户余额
									double money = paramsJsonObject.containsKey("money") ? paramsJsonObject.getDouble("money") : 0d;
									System.out.println("初始金额: " + money);
									meter.setAccountMoney(new BigDecimal(money));
									//剩余电量 concentrator_sn
									double leftElectricityCount = money / meter.getSinglePrice().doubleValue();
									meter.setElectricityCount(new BigDecimal(leftElectricityCount));
									meter.setOpenAccountState(1);
								}

								JSONArray dataJsonArray = map.containsKey("data") ? JSONUtil.parseArray(map.get("data").toString()) : null;
								if(dataJsonArray!=null && dataJsonArray.size() > 0){
									JSONObject data = (JSONObject)dataJsonArray.get(0);
									String dsp = data.containsKey("dsp") ? data.getStr("dsp") : "";
									meter.setOpenAccountDsp(dsp);
								}
								ret = meterMapper.updateById(meter);
								if(ret <= 0){

								}
							} else if (opRecord.getOpType().equals("recharge")) {//充值
								//记录 充值次数    在请求发送命令的时候  累加1  不保存数据，在此处 修改次数 ，保证正确性
								// [{"opr_id":"2aff090d13ce4fa4b5f568227ee27e41","resolve_time":"2022-09-02 11:11:06","status":"RESPONSE_FAIL",
								// "err_msg":"异常提示：85:充值次数错误",
								// "params":{"display_warning":30,"count":4,"account_id":"1","money":100,"price":0.5469,"pulloff_warning":5}}]
								JSONObject paramsJsonObject = map.containsKey("params") ? JSONUtil.parseObj(map.get("params").toString()) : null;
								if(paramsJsonObject!=null){
									int count = paramsJsonObject.getInt("count");
									meter.setPayCount(count);
									ret = meterMapper.updateById(meter);
									if(ret > 0){
										getSearchData(meter,22);
									}
								}
							} else if (opRecord.getOpType().equals("ele_write")) {//设置电表参数
//                                getSearchData(meter,opRecord.getTypeCode());
								//[{"opr_id":"fc16635395994dc2af36973bbc43b831","resolve_time":"2022-09-01 19:00:31","status":"SUCCESS",
								// "data":[{"type":22,"value":["0.00"],"dsp":" 购电次数: 0   剩余金额: 0.00 元  总用电量: 0.00 kWh "}]}]
								if(opRecord.getTypeCode()!=null){
									if(opRecord.getTypeCode() == 12){
										getSearchData(meter,35);//查询电费单价
									} else if(opRecord.getTypeCode() == 24){
										getSearchData(meter,38);//设置一级报警金额
									} else if(opRecord.getTypeCode() == 25){
										getSearchData(meter,39);//设置二级报警金额
									}
								}
							}
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("opRecordMapper insert error");
		}
	}

	@Override
	public String getSearchData(ElectricMeter meter, int type) {
		String response = "";
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_read";
			System.out.println("抄表   请求地址： " + url);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 1);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("type", type);
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("ele_read");
			record.setRemark("抄表数据");
			record.setTypeCode(type);
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			int ret = opRecordMapper.insert(record);
			if(ret > 0){
				response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return response;
	}

	@Override
	public int openElectric(ElectricMeter meter) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_control";
			System.out.println("合闸  同步 请求地址： " + url);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("type", 11); //10:拉闸   11:合闸
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("ele_control_open");
			record.setRemark("电表合闸");
			record.setTypeCode(11);
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public int closeElectric(ElectricMeter meter) {

		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_control";
			System.out.println("拉闸  同步 请求地址： " + url);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("type", 10); //10:拉闸   11:合闸
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("ele_control_close");
			record.setRemark("电表拉闸");
			record.setTypeCode(10);
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 *  清零 同步模式    电表必须在系统内关联用户
	 * @param meter
	 * @return
	 */
	@Override
	public int clearElectric(ElectricMeter meter) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_security/reset";
			System.out.println("设置电表参数  同步 请求地址： " + url);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			req.add(item);


			meter.setPayCount(0);
			meter.setOpenAccountState(0);
			ret = meterMapper.updateById(meter);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("reset");
			record.setRemark("电表清零");
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 *  异步模式
	 *   接口调用必须传递账户id
	 * @param meter
	 * @return
	 */
	@Override
	public int clearElectricAsync(ElectricMeter meter) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_security/reset";
			System.out.println("设置电表参数  异步 请求地址： " + url);

			Map<String, Object> params = new HashMap<>();
			params.put("account_id", "123456");

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("params", params);
			req.add(item);


			meter.setPayCount(0);
			meter.setOpenAccountState(0);
			ret = meterMapper.updateById(meter);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("reset");
			record.setRemark("电表清零");
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public int openAccount(ElectricMeter meter, Double initMoney) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_security/open_acount";
			System.out.println("开户请求地址： " + url);

			Map<String, Object> params = new HashMap<>();
			params.put("account_id", "1");
			params.put("count", "1");
			params.put("money", initMoney);
			params.put("display_warning", 30);//一级报警金额
			params.put("pulloff_warning", 5);//二级报警金额
			params.put("price", 0.5469);//电费单价

			//开户从1开始
			meter.setPayCount(1);
			ret = meterMapper.updateById(meter);
			if(ret <= 0){

			}

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("params", params);
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("open_account_async");
			record.setRemark("开户");
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public int rechargeElectric(ElectricMeter meter,int orderId, Double payMoney) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_security/recharge";

			Map<String, Object> params = new HashMap<>();
			params.put("money", payMoney);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("params", params);
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("reset");
			record.setRemark("充值: " + payMoney);
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public int rechargeElectricAsync(ElectricMeter meter,int orderId, Double payMoney) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_security/recharge";
			System.out.println("重置异步请求地址： " + url);

			Map<String, Object> params = new HashMap<>();
			params.put("account_id", "1");
			params.put("count", meter.getPayCount() + 1);
			params.put("money", payMoney);
			params.put("display_warning", 30);//一级报警金额
			params.put("pulloff_warning", 5);//二级报警金额
			params.put("price", meter.getSinglePrice());//电费单价


			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("retry_times", 3);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("params", params);
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setOrderId(orderId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("recharge");
			record.setRemark("充值: " + payMoney);
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public int setElectric(ElectricMeter meter, int type, Double value) {
		int ret = 0;
		try{
			Parameter parameter = parameterService.getParameterById(1);

			ElectricOpRecord record = new ElectricOpRecord();
			String oprId = ElectricMeterUtil.generateOperateId();
			String url = "http://api2.tqdianbiao.com/Api_v2/ele_write";
			System.out.println("设置电表参数 请求地址： " + url);

			Map<String, Object> params = new HashMap<>();
			params.put("p1", value);

			// 请求内容，调用接口所需要的数据（抄电表数据）
			List<Map<String, Object>> req = new ArrayList<>();
			Map<String, Object> item = new HashMap<>();
			item.put("opr_id", oprId);
			item.put("time_out", 0);
			item.put("must_online", true);
			item.put("cid", meter.getConcentratorSn());//集中器编号
			item.put("address", meter.getDeviceSn());//电表地址
			item.put("retry_times", 3);
			item.put("type", type);
			item.put("params", params);
			req.add(item);

			String request_content = JSONUtil.toJsonStr(req);

			record.setOprId(oprId);
			record.setCreateTime(new Date());
			record.setAddress(meter.getDeviceSn());
			record.setOpType("ele_write");
			record.setTypeCode(type);
			record.setRemark("设置电表参数");
			record.setRequestContent(request_content);
			record.setState(0);
			record.setDeviceCid(meter.getConcentratorSn());
			record.setElectricId(meter.getId());

			ret = opRecordMapper.insert(record);
			if(ret > 0){
				String response = ElectricMeterUtil.requestApiAsync(url, request_content,parameter,electric_notify_url);
				JSONObject jsonObject = JSONUtil.parseObj(response);
				System.out.println("请求参数： " + jsonObject);

				String status = jsonObject.getStr("status");
				if(!"SUCCESS".equals(status)) {
					System.out.println(jsonObject.getStr("error_msg"));
				} else {
					String response_content = jsonObject.getStr("response_content");
					System.out.println("response_content: " + response_content);
					JSONArray contentArray = JSONUtil.parseArray(response_content);
					int index = 1;
					System.out.println("返回结果：");
					for(int i = 0; i < contentArray.size(); ++i) {
						System.out.println("[" + index++ + "]");
						JSONObject contentObject = contentArray.getJSONObject(i);
						Set<String> keySet = contentObject.keySet();
						for(String key: keySet) {
							System.out.println(key + ": " + contentObject.get(key));
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}
}
